<?php
session_start();
// include settings and functions
include "../conn/database.php";
include "functions.php";
// if the user submit the form
if(isset($_POST['submit'])) {
	// initialize errors values
	$errors=0;
	$errors_text = '';
	// cleanning the post data from hacking attempt
	$post_data = clean($_POST);
	
	// empty post data verification
	if(empty($_POST['email'])) {
		$errors_text .= "Des champs sont vides<br />";
		$errors++;
	}
	
	// email verification
	if(!check_email($post_data['email']) ) {
		$errors_text .= "L'email n'est pas correct<br />";
		$errors++;
	}
	
	// if no errors we proceed
	if($errors == 0) {
		// data correction
		$email = strtolower(filter($post_data["email"]));
		
		//check the user and password
		$sql = "SELECT * FROM `T_PERSON` WHERE EMAIL_ADDRESS = '".$email."' limit 1";
		$res = mysql_query($sql);
		$rows = mysql_num_rows($res);
		$result = mysql_fetch_array($res);
		
		//if user exit and password right
		if($rows>0){
			// generating the user Password
			$password = generate_guid(6);
			
			$update_sql = "UPDATE `T_PERSON` SET `PASSWORD`= '".MD5($password)."' WHERE EMAIL_ADDRESS = '".$email."'";
			if(!mysql_query($update_sql)) {
					$errors_text .= mysql_error()."<br />";
					$errors++;
			} else {
				smtp_mail_forgetPW($email,"Your new password",$password,"verification@promessedunevie.com", "Promesse d'une Vie");
			}
		} else {
			$errors_text .= "User not exit.<br />";
			$errors++;
		}
	}
	if($errors == 0) {
		$arr['success'] = "1"; 
        $arr['msg'] = 'A new password has already sent to your email. Please check your email.';
	} else {
		$arr['success'] = "0"; 
        $arr['msg'] = $errors_text;
	}
	echo json_encode($arr);
}
?>